<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2018/11/28
 * Time: 11:42
 */

namespace App\Http\Controllers;


use App\Models\TaskCount;
use App\Models\TaskLog;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class TaskController extends Controller
{

    /**
     * 获取个人任务信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(){
        $user_id = auth()->guard('api')->id();
        $reData = TaskCount::where('user_id',$user_id)->where('created_at','>=',Carbon::today())->first();
        if(!$reData){
            $data = [
                'watch' => 0,  //每日观看视频最大奖励次数
                'shared_group' => 0, //每日分享到群最大奖励次数
                'shared_friends' => 0, //每日分享好友最大奖励次数
                'sign_in' => 0, //每日签到奖励次数
                'invite_friends' => 0, //每日邀请好友最大奖励次数
                'video_zans' => 0, //每日视频点赞最大奖励次数
                'video_collects' => 0, //每日视频收藏最大奖励次数
                'user_id' => $user_id
            ];
            $reData = TaskCount::create($data);
        }
        return $this->returnJson(0, '成功获取个人任务信息',$reData);
    }

    /**
     * 任务提交
     * @return \Illuminate\Http\JsonResponse
     */
    public function finish(){
        $task_type = (string)request('task_type','');
        $param_id = (int)request('param_id',0);
        Log::info($task_type.'-'.$param_id);
        if(!$task_type){
            return $this->returnJson(1, '未指定任务类型');
        }
        $configTask = config('task');
        if(!in_array($task_type,$configTask['request_only_type'])){
            return $this->returnJson(1, '参数类型错误');
        }
        $uid = auth()->guard('api')->id();
        if($task_type == 'shared_friends'){
            if($param_id == 0 && $uid == $param_id){
                return $this->returnJson(1, '参数错误');
            }
            $uid = $param_id;
            $param_id = auth()->guard('api')->id();
        }

        try{
            $this->finishTask($uid,$task_type,$param_id);
            return $this->returnJson(0 );
        }catch (\Exception $exception){
            Log::error($exception->getMessage());
            return $this->returnJson(1, '系统内部错误');
        }
    }

    /**
     * 获取任务配置信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function config(){
        $config = config( 'task');
        return $this->returnJson(0, '成功获取任务配置信息',$config);
    }

    /**
     * 获取个人任务积分记录
     * @return \Illuminate\Http\JsonResponse
     */
    public function scoreLog(){
        $user_id = auth()->guard('api')->id();
        $logData = TaskLog::where('user_id',$user_id)
            ->where('score','<>','0')
            ->orderBy('id','DESC')
            ->paginate(20);
        return $this->returnJson(0, '',$logData);
    }

}